package org.douxiaoban.client.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.gdata.data.douban.UserEntry;
import com.google.gdata.util.ServiceException;
import org.douxiaoban.client.R;
import org.douxiaoban.client.api.DoubanApi;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.Log;

import java.io.IOException;


public class LoginActivity extends Activity
{
    private DoubanApi _api;
    private ProgressDialog _progressDialog;
    private String oauthURL;
    private WebView webView ;
    private Button _btn_start_oauth;
    public static final int LOGIN_SUCCESS=10;
    public static final int FETCH_USERINFO_SUCCESS = 11;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);

        final LinearLayout validateLayout = (LinearLayout)this.
                findViewById(R.id.login_validate_layout);

       //enterNavigationActivity();

        _btn_start_oauth = (Button)findViewById(R.id.start_auth_btn);

        _api = App.getDouanApiInstance();
        _progressDialog = new ProgressDialog(this);
        _progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        _progressDialog.setIndeterminate(true);
        _progressDialog.setIcon(R.drawable.icon);
        _progressDialog.setMessage(getString(R.string.open_url));
        _progressDialog.setCancelable(true);
        _progressDialog.show();

        /** Initializ webview and disable web popwindow */
         webView = (WebView)
                this.findViewById(R.id.oauth_validate_webview);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setBackgroundColor(Color.WHITE);


        FetchOpenLoginUrl fetchOpenLoginUrl = new FetchOpenLoginUrl();
        new Thread(fetchOpenLoginUrl).start();


        _btn_start_oauth.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                _progressDialog.show();
                 FetchOauthURLObserver fetchOauthURLObserver = new FetchOauthURLObserver();
                new Thread(fetchOauthURLObserver).start();

                OauthObserver observer = new OauthObserver();
                       new Thread(observer).start();

            }
        });
    }

    class FetchOpenLoginUrl implements Runnable{
        public void run(){
            String url = "http://www.douban.com/accounts/login";
            webView.loadUrl(url);

            webView.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                  view.loadUrl(url);
                  return super.shouldOverrideUrlLoading(view, url);
                  //Super Method return super.shouldOverrideUrlLoading(view,url);
               }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);    //Super Method super.onLoadResource(view,url);
                }

                @Override
                 public void onPageFinished(WebView view, String url) {
                    if(_progressDialog.isShowing())
                       _progressDialog.cancel();

                      _btn_start_oauth.setVisibility(View.VISIBLE);

                    Toast.makeText(LoginActivity.this,"请在登录豆瓣后点击开始验证",2000).show();
                    super.onPageFinished(view, url);
                 }

            });
        }
    }

    class FetchOauthURLObserver implements Runnable{
        public void run(){
            String url = _api.getRequestTokenURLString();
            webView.loadUrl(url);

            Log.v("oauth:"+url);
            webView.setWebViewClient(new WebViewClient(){
                      @Override
                      public boolean shouldOverrideUrlLoading(WebView view, String url) {
                           view.loadUrl(url);
                          return super.shouldOverrideUrlLoading(view, url);
                           //Super Method return super.shouldOverrideUrlLoading(view,url);
                      }

                      @Override
                      public void onPageFinished(WebView view, String url) {
                      if(_progressDialog.isShowing())
                          _progressDialog.cancel();
                          _btn_start_oauth.setVisibility(View.GONE);
                          super.onPageFinished(view, url);

                      }
                  });

        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case LOGIN_SUCCESS:
                     _progressDialog.setMessage(getString(R.string.login_now));
                     _progressDialog.show();
                break;
                case FETCH_USERINFO_SUCCESS:
                    _progressDialog.dismiss();
                    enterNavigationActivity();
                    break;
                default:
                    break;

            }
        }
    };

    /**
     * Thread of Read oauth state,
     * break the funcion when the AccessTolekn get success
     */
    class OauthObserver implements Runnable{
        public void run() {
            Looper.prepare();
            int i = 0;
            while (i<100){
                i++;
                 if (null != _api.doubanService.getAccessToken()){

                     if(null !=_api.doubanService.accessor.accessToken){
                        sendMessage(handler,null,LOGIN_SUCCESS);
                        saveAccessToken();
                        sendMessage(handler,null,FETCH_USERINFO_SUCCESS);
                     }
                    break;
                }
                Log.v("Oauth Fail!!!!");
             }
            Looper.loop();
        }
       //TODO:Send intent to mian menu activity
    }

    private void saveAccessToken(){

        try {
            UserEntry userEntry =  _api.doubanService.getAuthorizedUser();

            if(userEntry!=null && userEntry.getUid()!=null && userEntry.getTitle()!=null){
//                _api.UID = userEntry.getUid();
                _api.UID = userEntry.getLink("icon", null).getHref();
                String[] uid_arr = _api.UID.split("/");
                String temp = uid_arr[uid_arr.length-1];
                temp = temp.substring(1,temp.length());
                _api.UID =  temp.split("-")[0];

                 App.userId = _api.UID;
                 App.username = userEntry.getTitle().getPlainText();

            }else{
                loginError();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }

        SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this);

        shared.edit().putString(Assistant.SETTING_ACCESS_TOKEN_KEY,App.
                getDouanApiInstance().doubanService.accessor.accessToken ).commit();
        shared.edit().putString(Assistant.SETTING_ACCESS_TOKEN_SECRET,
                App.getDouanApiInstance().doubanService.accessor.tokenSecret).commit();
        shared.edit().putString(Assistant.SETTING_UID, App.userId ).commit();
        shared.edit().putString(Assistant.SETTING_UNAME, App.username).commit();


    }

    private void enterNavigationActivity(){
        _progressDialog.dismiss();
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(LoginActivity.this,NavigationActivity.class);
        this.startActivity(intent);
        finish();
    }

    private void loginError(){
        Toast.makeText(this,getString(R.string.login_error),2000).show();
    }

      private void sendMessage(Handler handler, Bundle bundle, int what){
		Message msg = new Message();
		msg.what = what;
		msg.setData(bundle);
		handler.sendMessage(msg);
	}
}
